﻿using System;
using System.Linq;
using System.Collections.Generic;
using Pharmacy.Ultilities;
using Pharmacy.ExceptionHandling;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraPrinting;
using DevExpress.XtraGrid.Export;
using DevExpress.XtraExport;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using Pharmacy.Ultilities.BaseEventArgs;
using Pharmacy.Ultilities.Configurations;
using PharmacyPharnet.Core;
using Pharmacy.Data.Entity;
using Pharmacy.Data;
using Pharmacy.Business;
using Pharmacy.Business.Generator;
using System.Drawing;
using DevExpress.XtraEditors.Repository;
using PharmacyPharnet.MasterData;

namespace PharmacyPharnet.KinhDoanh
{
    public partial class FrmLichDatHang : DialogViewBase
    {
        #region Declarations
        /// <summary>
        /// Danh sách phiếu đặt hàng
        /// </summary>
        List<PhieuDatHang> rPhieuDatHang;
        /// <summary>
        /// Phiếu đặt hàng đang được chỉnh sửa
        /// </summary>
        PhieuDatHang currentPhieuDatHang;
        /// <summary>
        /// Danh sách các phiếu chi tiết bị xóa tạm
        /// </summary>
        List<PhieuDatHangChiTiet> lstPhieuDatHangChiTietDeleted;
        IObjectContext pharmacyContext;
        PhieuDatHangBO phieuDatHangBO;

        public const string CaptionLichDatHang_FromDateToDate = "Theo dõi đặt hàng từ {0} đến {1}";
        public const string CaptionLichDatHang_FromDate = "Theo dõi đặt hàng từ ngày {0}";
        public const string CaptionLichDatHang_ToDate = "Theo dõi đặt hàng đến ngày {0}";
        public const string CaptionLichDatHang_None = "Theo dõi đặt hàng";
        public const string CaptionLichDatHangDangChon = "Danh sách đặt hàng ngày {0}";
        public const string CaptionLichDatHangDangChon_None = "Danh sách đặt hàng";

        private Enums.ActionForm _CurrentAction ;
        
        protected Enums.ActionForm CurrentAction
        {
            get { return _CurrentAction; }
            set
            {
                _CurrentAction = value;
                ChangeButtonAction(_CurrentAction);
            }
        }        
        #endregion

        #region Constructors
        public FrmLichDatHang()
        {
            InitializeComponent();
        }
        #endregion

        #region Override Methods
        protected override void InitializeBO()
        {
            if (pharmacyContext == null)
                pharmacyContext = ObjectContextFactory.CreatePharmacyContext(Global.UserName, Global.CurrentConnectionString);
            if (phieuDatHangBO == null)
                phieuDatHangBO = new PhieuDatHangBO(pharmacyContext);
        }

        protected override void PopulateStaticData()
        {
            SetDefaultDateRange();
            if (lstPhieuDatHangChiTietDeleted == null)
                lstPhieuDatHangChiTietDeleted = new List<PhieuDatHangChiTiet>();
        }

        protected override void PopulateData()
        {
            LoadPhieuDatHang();
        }
        #endregion

        #region Custom Methods
        /// <summary>
        /// Set default range daet to filter data
        /// </summary>
        public void SetDefaultDateRange()
        {
            DateTime fromdate = Convert.ToDateTime(ConfigManager.DIOConfig.FromDate);
            DateTime todate = Convert.ToDateTime(ConfigManager.DIOConfig.ToDate);
            int dateRange = Convert.ToInt32(ConfigManager.DIOConfig.InLastDays);
            dteFromDate.EditValue = fromdate;
            dteToDate.EditValue = fromdate.AddDays(dateRange);
            string caption = string.Format(CaptionLichDatHang_FromDateToDate, fromdate.ToShortDateString(), todate.ToShortDateString());
            grpList.Text = caption;
        }

        /// <summary>
        /// Set image for Delete buttons, Edit buttons in gridcontrol
        /// </summary>
        public void LoadLayoutGrid()
        {
            //Set image for Delete button
            Image img = Image.FromFile(IOHelper.CombinePath(IOHelper.ExecutePath, @"Images\delete.png"));
            //btnDelete = grvPhieuDeXuatdatHang.Columns[gcLDHDelete.FieldName].ColumnEdit as RepositoryItemButtonEdit;
            btnLDHDelete.Buttons[0].Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph;
            btnLDHDelete.Buttons[0].Image = img.GetThumbnailImage(18, 18, null, IntPtr.Zero);

            // Set image for Edit button
            img = Image.FromFile(IOHelper.CombinePath(IOHelper.ExecutePath, @"Images\edit.png"));
            btnLDHEdit.Buttons[0].Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph;
            btnLDHEdit.Buttons[0].Image = img.GetThumbnailImage(18, 18, null, IntPtr.Zero);

            //Set image for Delete button
            img = Image.FromFile(IOHelper.CombinePath(IOHelper.ExecutePath, @"Images\delete.png"));
            btnLDHChiTietDelete.Buttons[0].Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph;
            btnLDHChiTietDelete.Buttons[0].Image = img.GetThumbnailImage(18, 18, null, IntPtr.Zero); 

            CurrentAction = Enums.ActionForm.None;

            
        }

        private void OpenFile(string fileName)
        {
            if (MessageBox.Show("Do you want to open this file?", "Export File", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    System.Diagnostics.Process process = new System.Diagnostics.Process();
                    process.StartInfo.FileName = fileName;
                    process.StartInfo.Verb = "Open";
                    process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                    process.Start();
                }
                catch (Exception ex)
                {
                    string message = "Cannot find an application on your system suitable for openning the file with exported data.";
                    ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                    MessageBox.Show(message);
                }
            }
        }

        private string ShowSaveFileDialog(string title, string filter)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            string name = Application.ProductName;
            int n = name.LastIndexOf(".") + 1;
            if (n > 0) name = name.Substring(n, name.Length - n);
            dlg.Title = "Export To " + title;
            //dlg.FileName = name;
            dlg.FileName = "filename";
            dlg.Filter = filter;
            if (dlg.ShowDialog() == DialogResult.OK) return dlg.FileName;
            return "";
        }

        //IExportProvider provider
        private void ExportTo(GridView currentView, string fileName)
        {
            grdDanhSachSanPhamDatHang.FindForm().Refresh();
            currentView.OptionsPrint.PrintDetails = true;
            currentView.OptionsPrint.ExpandAllDetails = true;
            currentView.OptionsPrint.ExpandAllGroups = true;
            currentView.OptionsPrint.AutoWidth = false;
            XlsExportOptions option = new XlsExportOptions();
            option.ShowGridLines = true;
            currentView.ExportToXls(fileName, option);
        }

        private void ExportToExcelWithoutDetail(GridView currentView, string fileName)
        {
            grdDanhSachSanPhamDatHang.FindForm().Refresh();
            if (currentView == null) return;
            GridViewExportLink gvlink;
            using (ExportXlsProvider provider = new ExportXlsProvider(fileName))
            {
                gvlink = (GridViewExportLink)currentView.CreateExportLink(provider);
                gvlink.ExpandAll = true;
                gvlink.ExportDetails = true;
                gvlink.ExportAll = true;
                gvlink.ExportTo(true);
            }
        }

        /// <summary>
        /// Lấy danh sách các phiếu đặt hàng có status = Draft (5)
        /// </summary>
        private void LoadPhieuDatHang()
        {
            rPhieuDatHang = phieuDatHangBO.ListLichDatHang();
            DateTime fromDate, toDate;
            if (dteFromDate.Text != string.Empty && dteToDate.Text != string.Empty)
            {
                fromDate = DateTime.Parse(dteFromDate.EditValue.ToString());
                toDate = DateTime.Parse(dteToDate.EditValue.ToString());
                rPhieuDatHang = rPhieuDatHang.AsQueryable()
                                .Where(pdh => pdh.DocumentDate >= fromDate && pdh.DocumentDate <= toDate)
                                .ToList();
            }
            else if (dteFromDate.Text != string.Empty && dteToDate.Text == string.Empty)
            {
                fromDate = DateTime.Parse(dteFromDate.EditValue.ToString());
                rPhieuDatHang = rPhieuDatHang.AsQueryable()
                                .Where(pdh => pdh.DocumentDate >= fromDate)
                                .ToList();
            }
            else if (dteFromDate.Text == string.Empty && dteToDate.Text != string.Empty)
            {
                toDate = DateTime.Parse(dteToDate.EditValue.ToString());
                rPhieuDatHang = rPhieuDatHang.AsQueryable()
                                .Where(pdh => pdh.DocumentDate <= toDate)
                                .ToList();
            }
            else
            {
                rPhieuDatHang = rPhieuDatHang.AsQueryable().ToList();
            }
            grdPhieuDeXuatdatHang.DataSource = rPhieuDatHang;
            grvPhieuDeXuatdatHang.BestFitColumns();
        }

        /// <summary>
        /// Bind data into controls before editing
        /// </summary>
        private void BindDataToControlEdit()
        {
            if (currentPhieuDatHang != null)
            {
                string caption = string.Format(CaptionLichDatHangDangChon, currentPhieuDatHang.DocumentDate.GetValueOrDefault().ToShortDateString());
                grpDanhSachDatHang.Text = caption;
                txtName.EditValue = currentPhieuDatHang.Code;
                txtDescription.EditValue = currentPhieuDatHang.Note;
                dteLDHDocumentDate.EditValue = currentPhieuDatHang.DocumentDate;
                grdDanhSachSanPhamDatHang.DataSource = currentPhieuDatHang.PhieuDatHangChiTiets;
                grvPhieuDeXuatdatHang.RefreshData();
            }
            else
            {
                string caption = CaptionLichDatHangDangChon_None;
                grpDanhSachDatHang.Text = caption;
                txtName.EditValue = string.Empty;
                txtDescription.EditValue = string.Empty;
                dteLDHDocumentDate.EditValue = null;
                grdDanhSachSanPhamDatHang.DataSource = null;
                grvDanhSachSanPhamDatHang.RefreshData();
            }
        }

        /// <summary>
        /// Enable/Disable buttons after changed status of form
        /// </summary>
        /// <param name="status">if action is Edit or New, status will be true, otherwise is false</param>
        private void ChangeButtonAction(bool status)
        {
            btnNew.Enabled = !status;
            btnLDHChiTietDelete.Enabled = !status;
            btnCancel.Enabled = status;
            btnLDHSave.Enabled = status;


        }

        /// <summary>
        /// Enable/Disable buttons after changed status of form
        /// </summary>
        /// <param name="action">includes: None/New/Edit</param>
        protected virtual void ChangeButtonAction(Enums.ActionForm action)
        {
            ChangeButtonAction(action == Enums.ActionForm.Edit || action == Enums.ActionForm.New);
            _CurrentAction = action;
        }

        /// <summary>
        /// Reset data of current PhieuDatHand after clicking on Cancel button
        /// </summary>
        private void ResetAllData()
        {
            if (CurrentAction == Enums.ActionForm.Edit)
            {
                if (currentPhieuDatHang.PhieuDatHangChiTiets != null && currentPhieuDatHang.PhieuDatHangChiTiets.Count > 0)
                {
                    List<PhieuDatHangChiTiet> lstChiTiet = currentPhieuDatHang.PhieuDatHangChiTiets.ToList();
                    PhieuDatHangChiTiet pbgChiTiet;
                    for (int i = lstChiTiet.Count - 1; i >= 0; i--)
                    {
                        pbgChiTiet = lstChiTiet[i];
                        if (pbgChiTiet.EntityState == System.Data.EntityState.Added)
                            currentPhieuDatHang.PhieuDatHangChiTiets.Remove(pbgChiTiet);
                    }

                }

                if (lstPhieuDatHangChiTietDeleted.Count > 0)
                {
                    foreach (PhieuDatHangChiTiet pdhDetail in lstPhieuDatHangChiTietDeleted)
                    {
                        pdhDetail.PhieuDatHang = currentPhieuDatHang;
                        currentPhieuDatHang.PhieuDatHangChiTiets.Attach(pdhDetail);
                    }
                    lstPhieuDatHangChiTietDeleted.Clear();
                }

                pharmacyContext.Reload(System.Data.Objects.RefreshMode.StoreWins, currentPhieuDatHang);
                pharmacyContext.Reload(System.Data.Objects.RefreshMode.StoreWins, currentPhieuDatHang.PhieuDatHangChiTiets);
            }
            currentPhieuDatHang = null;
            lstPhieuDatHangChiTietDeleted.Clear();
            BindDataToControlEdit();
            CurrentAction = Enums.ActionForm.None;

        }

        /// <summary>
        /// Get list master item of current PhieuDatHang, it's helpful for user cannot select duplicated master item.
        /// </summary>
        private List<MasterItem> GetExistedMasterItem()
        {
            if (currentPhieuDatHang != null && currentPhieuDatHang.PhieuDatHangChiTiets != null && currentPhieuDatHang.PhieuDatHangChiTiets.Count >0)
            {
                List<PhieuDatHangChiTiet> lstExistedPhieuDatHangChiTiet = currentPhieuDatHang.PhieuDatHangChiTiets.ToList();
                List<MasterItem> lstExistedMasterItem = new List<MasterItem>();
                foreach (PhieuDatHangChiTiet pdhChiTiet in lstExistedPhieuDatHangChiTiet)
                {
                    lstExistedMasterItem.Add(pdhChiTiet.MasterItem);
                }
                return lstExistedMasterItem;
            }
            return null;
        }

        #endregion

        #region Event Handlers
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                string fileName = ShowSaveFileDialog("Microsoft Excel Document", "Microsoft Excel|*.xls");
                if (fileName != "")
                {
                    //new ExportXlsProvider(fileName)
                    //ExportTo(this.MainView as GridView, fileName);
                    //ExportTo(fileName);
                    string msg = Pharmacy.Ultilities.Resources.SR.Instance.GetString(Constant.EXPORTDATA_INCLUDEDETAIL);
                    if (MessageBox.Show(msg, Pharmacy.Ultilities.Resources.SR.Instance.GetString(Constant.EXPORTDATA_MESSAGETITLE), MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        ExportTo(grvDanhSachSanPhamDatHang, fileName);
                    }
                    else
                    {
                        ExportToExcelWithoutDetail(grvDanhSachSanPhamDatHang, fileName);
                    }
                    OpenFile(fileName);
                }
            }
            catch (Exception ex)
            {

                ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(ex.Message);
            }
        }

        private void FrmListBase_Load(object sender, EventArgs e)
        {
            try
            {
                LoadLayoutGrid();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Vui lòng liên hệ Người quản trị hệ thống để được hỗ trợ.");
                ExceptionHandler.LogWriter.Write(ex, ExceptionHandler.LOG_CAT_GENERAL);
                this.Close();
            }
        }

        private void grvMasterData_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            try
            {
                if (e.Info.IsRowIndicator)
                {
                    if (e.RowHandle != GridControl.NewItemRowHandle && e.RowHandle != GridControl.AutoFilterRowHandle)
                    {
                        if (e.RowHandle < 0)
                        {
                            e.Info.DisplayText = "";
                        }
                        else
                        {
                            e.Info.DisplayText = (e.RowHandle + 1).ToString();
                        }
                    }
                    if (e.RowHandle == GridControl.AutoFilterRowHandle)
                    {
                        e.Info.ImageIndex = -1;
                        e.Info.DisplayText = "Filter";
                    }
                }
            }
            catch (Exception ex)
            {

                ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(ex.Message);
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                if (dteFromDate.Text != string.Empty && dteToDate.Text != string.Empty && Convert.ToDateTime(dteFromDate.EditValue) > Convert.ToDateTime(dteToDate.EditValue))
                {
                    dteFromDate.ErrorText = "[Từ Ngày] phải nhỏ hơn [Đến Ngày]";
                    return;
                }
                else
                {
                    string caption =string.Empty;
                    if (dteFromDate.Text != string.Empty && dteToDate.Text != string.Empty)
                    {
                        caption = string.Format(CaptionLichDatHang_FromDateToDate, Convert.ToDateTime(dteFromDate.EditValue).ToShortDateString(), Convert.ToDateTime(dteToDate.EditValue).ToShortDateString());
                    }
                    else if (dteFromDate.Text != string.Empty && dteToDate.Text == string.Empty)
                        caption = string.Format(CaptionLichDatHang_FromDate, Convert.ToDateTime(dteFromDate.EditValue).ToShortDateString());
                    else if (dteFromDate.Text == string.Empty && dteToDate.Text != string.Empty)
                        caption = string.Format(CaptionLichDatHang_ToDate, Convert.ToDateTime(dteToDate.EditValue).ToShortDateString());
                    else
                        caption = CaptionLichDatHang_None;
                    grpList.Text = caption;

                    LoadPhieuDatHang();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Vui lòng liên hệ Người quản trị hệ thống để được hỗ trợ.");
                ExceptionHandler.LogWriter.Write(ex, ExceptionHandler.LOG_CAT_GENERAL);
                this.Close();
            }
        }

        private void grvPhieuDeXuatdatHang_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            try
            {
                if (e.Info.IsRowIndicator)
                {
                    if (e.RowHandle != GridControl.NewItemRowHandle && e.RowHandle != GridControl.AutoFilterRowHandle)
                    {
                        if (e.RowHandle < 0)
                        {
                            e.Info.DisplayText = "";
                        }
                        else
                        {
                            e.Info.DisplayText = (e.RowHandle + 1).ToString();
                        }
                    }
                    if (e.RowHandle == GridControl.AutoFilterRowHandle)
                    {
                        e.Info.ImageIndex = -1;
                        e.Info.DisplayText = "Filter";
                    }
                }
            }
            catch (Exception ex)
            {

                ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(ex.Message);
            }
        }

        private void grdPhieuDeXuatdatHang_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                PhieuDatHang tmpPhieuDatHang = grvPhieuDeXuatdatHang.GetRow(grvPhieuDeXuatdatHang.FocusedRowHandle) as PhieuDatHang;
                if (tmpPhieuDatHang == null)
                {
                    return;
                }
                GridHitInfo ghi = grvPhieuDeXuatdatHang.CalcHitInfo((e as MouseEventArgs).Location);
                if (!ghi.InRow)
                {
                    return;
                }

                currentPhieuDatHang = tmpPhieuDatHang;
                string caption = string.Format(CaptionLichDatHangDangChon, currentPhieuDatHang.DocumentDate.GetValueOrDefault().ToShortDateString());
                grpDanhSachDatHang.Text = caption;
            }
            catch (Exception ex)
            {

                ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        private void btnNew_Click(object sender, EventArgs e)
        {
            try
            {
                currentPhieuDatHang = new PhieuDatHang();
                DateTime currentdate = pharmacyContext.GetCurrentDateTime();
                currentPhieuDatHang.Code = IdentityGeneratorHelper.GetNextNumber(Enums.GeneratorObjectType.PhieuDatHangGenerator, currentdate, null, pharmacyContext);
                currentPhieuDatHang.DocumentDate = currentdate;
                currentPhieuDatHang.Status = (int)Enums.PhieuDatHangStatus.Draft;
                BindDataToControlEdit();
                CurrentAction = Enums.ActionForm.New;
            }
            catch (Exception ex)
            {

                ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(ex.Message);
            }
        }

        private void btnLDHDelete_ButtonPressed(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph)
                {
                    currentPhieuDatHang = grvPhieuDeXuatdatHang.GetRow(grvPhieuDeXuatdatHang.FocusedRowHandle) as PhieuDatHang;
                    if (currentPhieuDatHang != null)
                    {
                        if (MessageBox.Show("Bạn có muốn xóa lịch đặt hàng đang được chọn không?", "Xóa  lịch đặt hàng", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                        {
                            string message = string.Empty;
                            phieuDatHangBO.DeletePhieuDatHang(currentPhieuDatHang.ID, out message);
                            if (message.Length > 0)
                            {
                                MessageBox.Show(message);
                                return;
                            }
                            else
                            {
                                LoadPhieuDatHang();
                                grvPhieuDeXuatdatHang.RefreshData();
                                currentPhieuDatHang = null;
                                string caption = CaptionLichDatHangDangChon_None;
                                grpDanhSachDatHang.Text = caption;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(ex.Message);
            }
        }

        private void btnLDHEdit_ButtonPressed(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                currentPhieuDatHang = grvPhieuDeXuatdatHang.GetRow(grvPhieuDeXuatdatHang.FocusedRowHandle) as PhieuDatHang;
                BindDataToControlEdit();
                CurrentAction = Enums.ActionForm.Edit;
            }
            catch (Exception ex)
            {

                ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(ex.Message);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                ResetAllData();
            }
            catch (Exception ex)
            {

                ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(ex.Message);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                List<PhieuDatHangChiTiet> lstDeletedItem = new List<PhieuDatHangChiTiet>();
                string message = string.Empty;
                if (CurrentAction == Enums.ActionForm.None)
                    phieuDatHangBO.CreateNewPhieuDatHang(currentPhieuDatHang);
                else
                    phieuDatHangBO.EditPhieuDatHang(currentPhieuDatHang, lstDeletedItem, out message);
                //pharmacyContext.Reload(System.Data.Objects.RefreshMode.StoreWins, rPhieuDatHang);
                LoadPhieuDatHang();
                grvPhieuDeXuatdatHang.RefreshData();
                CurrentAction = Enums.ActionForm.None;
            }
            catch (Exception ex)
            {

                ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(ex.Message);
            }
            
        }

        private void grvDanhSachSanPhamDatHang_Click(object sender, EventArgs e)
        {
             try
            {
                if (currentPhieuDatHang != null)
                {
                    GridHitInfo ghi = grvDanhSachSanPhamDatHang.CalcHitInfo((e as MouseEventArgs).Location);
                    if (!ghi.InRow)
                    {
                        return;
                    }
                    if (grvDanhSachSanPhamDatHang.FocusedRowHandle < 0)
                    {
                        List<MasterItem> lstExistedMasterItem = GetExistedMasterItem();
                        FrmMasterItemSelection frm = new FrmMasterItemSelection(pharmacyContext, lstExistedMasterItem);
                        frm.RowSelected += new FrmMasterItemSelection.RowSelectedEventHandler(SelectedMasterItem);
                        frm.ShowDialog();
                    }
                }
            }
            catch (Exception ex)
            {

                ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(ex.Message);
            }
        }

        void SelectedMasterItem(object sender, RowSelectedArgs e)
        {
            List<MasterItem> lstMasterItem = e.CurrentListMasterItem;
            if (lstMasterItem != null && lstMasterItem.Count > 0)
            {
                PhieuDatHangChiTiet pdhChiTiet;
                int i =1;
                foreach (MasterItem item in lstMasterItem)
                {
                    pdhChiTiet = new PhieuDatHangChiTiet();
                    pdhChiTiet.MasterItem = item;
                    pdhChiTiet.LineNo = i;
                    pdhChiTiet.Quantity = 0;
                    pdhChiTiet.StockInQty = 0;
                    pdhChiTiet.UnitCost = 0;
                    pdhChiTiet.UnitOfMeasure = item.UnitOfMeasure;
                    pdhChiTiet.UnStockInQty = 0;
                    pdhChiTiet.VATAmount = 0;
                    pdhChiTiet.VATRate = 0;
                    currentPhieuDatHang.PhieuDatHangChiTiets.Add(pdhChiTiet);
                    i++;
                }
                BindDataToControlEdit();
            }
        }

        private void btnLDHChiTietDelete_ButtonPressed(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph)
                {
                    PhieuDatHangChiTiet pdhDetail = grvDanhSachSanPhamDatHang.GetRow(grvDanhSachSanPhamDatHang.FocusedRowHandle) as PhieuDatHangChiTiet;
                    if (pdhDetail != null)
                    {
                        
                        if (pdhDetail.EntityState != System.Data.EntityState.Added)
                            lstPhieuDatHangChiTietDeleted.Add(pdhDetail);
                        currentPhieuDatHang.PhieuDatHangChiTiets.Remove(pdhDetail);
                        grvDanhSachSanPhamDatHang.RefreshData();
                    }
                }
            }
            catch (Exception ex)
            {

                ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(ex.Message);
            }
        }

    }
}
